package divestoclimb.checklist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import divestoclimb.checklist.data.Template;
import divestoclimb.checklist.storage.DbAdapter;
import divestoclimb.checklist.storage.XmlAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EditTemplate extends Activity implements Button.OnClickListener {

	// The possible actions to pass to this activity
	public static final int ACTION_NEW = 1;
	public static final int ACTION_EDIT = 2;
	
	private static final int RESULT_SAVE_TEMPLATE = 3;

	// The action we are taking: new or edit
	protected int mAction;
	// If we are editing, mId is the ID of the existing template.
	protected long mId;
	// If this is a new Template, this is the category to create it in
	protected long mCategoryId;

	private Button mCategoryButton;
	
	// The Template we are editing
	protected Template mTemplate;
	
	// The EditText field with the new text in it
	protected EditText mEditText, mVersion;

	// This string is used to restore the previously entered text from a previous
	// state.
	protected String mSavedText, mSavedVersion;
	protected Long mSavedCategory;
	
	private String mExportPath;

	protected DbAdapter mDbHelper;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Bundle params = icicle != null? icicle: getIntent().getExtras();

		mDbHelper = new DbAdapter(this);

		mAction = params.getInt("action");
		if(mAction == ACTION_EDIT) {
			mId = params.getLong(DbAdapter.KEY_TEMPLATE_ID);
		} else {
			mTemplate = null;
		}

		// Try to retrieve the text and category that we had before the activity was
		// stopped
		if(icicle != null) {
			mSavedText = icicle.getString(DbAdapter.KEY_ITEM_TEXT);
			mSavedVersion = icicle.getString(DbAdapter.KEY_TEMPLATE_VERSION);
			mSavedCategory = icicle.getLong(DbAdapter.KEY_TEMPLATE_CATEGORY);
		} else {
			mSavedText = mSavedVersion = null;
			if(mAction == ACTION_EDIT) {
				mSavedCategory = null;
			} else {
				mSavedCategory = params.getLong(DbAdapter.KEY_TEMPLATE_CATEGORY);
			}
		}

		setContentView(R.layout.template_info);

		mEditText = (EditText)findViewById(R.id.content);
		mVersion = (EditText)findViewById(R.id.version);

		mCategoryButton = (Button)findViewById(R.id.cat_button);
		mCategoryButton.setOnClickListener(this);

		// Initialize the prompt
		TextView prompt = (TextView)findViewById(R.id.prompt);
		prompt.setText(getResources().getString(R.string.template_name_prompt));

		// Set up the button listener
		Button ok = (Button)findViewById(R.id.button_ok);
		ok.setOnClickListener(this);
		Button export = (Button)findViewById(R.id.button_export);
		export.setOnClickListener(this);
		Button cancel = (Button)findViewById(R.id.button_cancel);
		cancel.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		mDbHelper.open();
		if(mAction == ACTION_EDIT) {
			// Look up the template we're editing
			mTemplate = mDbHelper.fetchTemplate(mId);
			
			// Populate the EditText with the existing name of this template, or
			// the saved text from the previous instance if the activity was stopped
			// and resumed
			mEditText.setText(mTemplate.getName());
			mVersion.setText(mTemplate.getVersion());
			mCategoryId = mTemplate.getCategory().getID();
		}
		if(mSavedText != null) {
			mEditText.setText(mSavedText);
		}
		if(mSavedVersion != null) {
			mVersion.setText(mSavedVersion);
		}
		if(mSavedCategory != null) {
			mCategoryId = mSavedCategory;
		}

		mCategoryButton.setText(mDbHelper.fetchCategory(mCategoryId).getName());

		if(mExportPath != null) {
			// Export the template to the given location
			try {
				File path = new File(mExportPath);
				mExportPath = null;
				if(! path.getParentFile().isDirectory()) {
					path.getParentFile().mkdirs();
				}
				FileWriter buffer = new FileWriter(path);
				XmlAdapter xmlHelper = new XmlAdapter(mDbHelper);
				xmlHelper.writeTemplate(mId, buffer);
				buffer.flush();
				buffer.close();
				Toast.makeText(this, R.string.template_saved, Toast.LENGTH_SHORT).show();
			} catch(IOException e) {
				String message;
				if(e instanceof FileNotFoundException) {
					message = getString(R.string.file_not_found);
				} else {
					message = getString(R.string.save_error);
				}
				Toast.makeText(this, String.format(message, e.getMessage()), Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putLong("action", mAction);
		if(mAction == ACTION_EDIT) {
			outState.putLong(DbAdapter.KEY_TEMPLATE_ID, mId);
		}
		outState.putString(DbAdapter.KEY_ITEM_TEXT, mEditText.getText().toString());
		outState.putString(DbAdapter.KEY_TEMPLATE_VERSION, mVersion.getText().toString());
		outState.putLong(DbAdapter.KEY_TEMPLATE_CATEGORY, mCategoryId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		mDbHelper.close();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(resultCode, requestCode, data);
		if(resultCode == RESULT_OK) {
			switch(requestCode) {
			case SelectCategory.CODE_CATEGORY_CHANGE:
				mSavedCategory = data.getExtras().getLong(DbAdapter.KEY_CATEGORY_ID);
				break;
			case RESULT_SAVE_TEMPLATE:
				mExportPath = data.getExtras().getString(SaveDialog.PARAM_NAME);
			}
		}
	}

	public void onClick(View v) {
		Intent i;
		switch(v.getId()) {
		case R.id.button_cancel:
			setResult(RESULT_CANCELED);
			finish();
			break;
		case R.id.button_ok:
			if(mTemplate == null) {
				// We must be creating a new Template
				mTemplate = new Template(mEditText.getText().toString());
			} else {
				// Update the name
				mTemplate.setName(mEditText.getText().toString());
			}
			mTemplate.setVersion(mVersion.getText().toString());
			mTemplate.setCategory(mDbHelper.fetchCategory(mCategoryId));

			if(mTemplate.save(mDbHelper)) {
				i = new Intent()
					.putExtra(DbAdapter.KEY_TEMPLATE_ID, mTemplate.getID());
				setResult(RESULT_OK, i);
				finish();
			} else {
				Toast.makeText(this, R.string.template_save_failed, Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.button_export:
			i = new Intent(this, SaveDialog.class);
			Template t = mDbHelper.fetchTemplate(mId);
			i.putExtra(SaveDialog.PARAM_DEFAULT_NAME,
					t.getName()+"."+D2cChecklist.TEMPLATE_EXTENSION);
			i.putExtra(SaveDialog.PARAM_LOCATION, D2cChecklist.TEMPLATE_DEFAULT_LOCATION.getAbsolutePath());
			startActivityForResult(i, RESULT_SAVE_TEMPLATE);
			break;
		case R.id.cat_button:
			startActivityForResult(new Intent(this, SelectCategory.class), SelectCategory.CODE_CATEGORY_CHANGE);
		}
	}
}